
package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.goodsbean.goodsbo.*;
import com.cskaoyan.bean.goodsbean.goodsvo.*;
import com.cskaoyan.bean.goodsbean.wxbean.ChannelBean;
import com.cskaoyan.bean.groupon.GrouponListVO;
import com.cskaoyan.mapper.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.System;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: whyccz-mall-project
 * @description:
 * @create: 2021-06-04 19:42
 **/
@Service
public class GoodsServiceImpl implements GoodsService {

	@Autowired
	GoodsMapper goodsMapper;
	@Autowired
	GoodsAttributeMapper attributeMapper;
	@Autowired
	GoodsProductMapper productMapper;
	@Autowired
	GoodsSpecificationMapper specificationMapper;
	@Autowired
	GoodsCategoryMapper categoryMapper;
	@Autowired
	GoodsBrandMapper brandMapper;


	@Override
	public GoodsListVO selectGoodsList(String goodsSn, String name, Integer page, Integer limit, String sort, String order) {

		PageHelper.startPage(page,limit);//调用分页插件,查询时会进行拼接

		//每个service方法创建一个example对象
		GoodsExample goodsExample = new GoodsExample();
		//排序信息
		goodsExample.setOrderByClause(sort+" "+order);
		GoodsExample.Criteria criteria = goodsExample.createCriteria();
		if (goodsSn !=null&& !"".equals(goodsSn)){
			criteria.andGoodsSnLike("%" + goodsSn + "%");
		}
		if (name != null && !"".equals(name)) {
			criteria.andNameLike("%"+name+"%");
		}
		criteria.andDeletedEqualTo(false);

		List<Goods> goods = goodsMapper.selectByExampleWithBLOBs(goodsExample);

		//获得分页信息
		PageInfo<Goods> goodsPageInfo = new PageInfo<>(goods);
		long total = goodsPageInfo.getTotal();

		GoodsListVO goodsListVO = new GoodsListVO();
		goodsListVO.setTotal(total);
		goodsListVO.setItems(goods);

		return goodsListVO;
	}
	@Transactional
	@Override
	public void createGoods(CreateGoodsBO createGoodsBO) {

		GoodsBean goodsBean = createGoodsBO.getGoods();
		Goods goods = new Goods();
		goods.setGoodsSn(goodsBean.getGoodsSn());
		goods.setBrandId(goodsBean.getBrandId());
		goods.setName(goodsBean.getName());
		goods.setCounterPrice(new BigDecimal(goodsBean.getCounterPrice()));//字符串转BigDecimal
		goods.setRetailPrice(new BigDecimal(goodsBean.getRetailPrice()));//字符串转BigDecimal
		goods.setIsHot(goodsBean.isHot());
		goods.setIsNew(goodsBean.isNew());
		goods.setIsOnSale(goodsBean.isOnSale());
		goods.setUnit(goodsBean.getUnit());
		goods.setKeywords(goodsBean.getKeywords());
		goods.setCategoryId(goodsBean.getCategoryId());
		goods.setBrief(goodsBean.getBrief());
		goods.setPicUrl(goodsBean.getPicUrl());
		goods.setDetail(goodsBean.getDetail());
		goods.setAddTime(new Timestamp(System.currentTimeMillis()));
		goods.setUpdateTime(new Timestamp(System.currentTimeMillis()));
		String join = String.join(",", goodsBean.getGallery());
		String[] split = join.split(",");
		goods.setGallery(split);//字符串链表转为字符串
		//时间直接在sql中设置为now()
		goodsMapper.insertSelective(goods);
		//在mapper.xml中设置使用主键,可以获取插入后的主键
		Integer goodsId = goods.getId();


		List<ProductsBean> products = createGoodsBO.getProducts();
		for (ProductsBean product : products) {
			GoodsProduct goodsProduct = new GoodsProduct();
			goodsProduct.setPrice(new BigDecimal(product.getPrice()));
			goodsProduct.setNumber(Integer.valueOf(product.getNumber()));//传的是string 要确保是数字
			goodsProduct.setUrl(product.getUrl());
			//规格字符串链表转为字符串,以逗号分割
			String[] specSplit = String.join(",", product.getSpecifications()).split(",");
			goodsProduct.setSpecifications(specSplit);
			goodsProduct.setGoodsId(goodsId);
			goodsProduct.setAddTime(new Timestamp(System.currentTimeMillis()));
			goodsProduct.setUpdateTime(new Timestamp(System.currentTimeMillis()));
			productMapper.insertSelective(goodsProduct);
		}
		List<SpecificationsBean> specifications = createGoodsBO.getSpecifications();
		for (SpecificationsBean specification : specifications) {
			GoodsSpecification goodsSpecification = new GoodsSpecification();
			goodsSpecification.setGoodsId(goodsId);
			goodsSpecification.setSpecification(specification.getSpecification());
			goodsSpecification.setValue(specification.getValue());
			goodsSpecification.setPicUrl(specification.getPicUrl());
			goodsSpecification.setAddTime(new Timestamp(System.currentTimeMillis()));
			goodsSpecification.setUpdateTime(new Timestamp(System.currentTimeMillis()));
			specificationMapper.insertSelective(goodsSpecification);

		}
		List<AttributesBean> attributes = createGoodsBO.getAttributes();
		for (AttributesBean attribute : attributes) {
			GoodsAttribute goodsAttribute = new GoodsAttribute();
			goodsAttribute.setGoodsId(goodsId);
			goodsAttribute.setValue(attribute.getValue());
			goodsAttribute.setAttribute(attribute.getAttribute());
			goodsAttribute.setAddTime(new Timestamp(System.currentTimeMillis()));
			goodsAttribute.setUpdateTime(new Timestamp(System.currentTimeMillis()));
			attributeMapper.insertSelective(goodsAttribute);
		}

	}

	@Override
	public GoodsDetailVO getGoodsDetail(Integer id) {

		GoodsExample goodsExample = new GoodsExample();
		goodsExample.createCriteria().andIdEqualTo(id);
		List<Goods> goodsList = goodsMapper.selectByExampleWithBLOBs(goodsExample);
		Goods goods = goodsList.get(0);

		Integer categoryId = goods.getCategoryId();//种类id
		Integer goodsId = goods.getId();

		//category
		ArrayList<Integer> categoryIds = new ArrayList<>();
		if (categoryId!=0){
			GoodsCategory goodsCategory = categoryMapper.selectByPrimaryKey(categoryId);
			Integer pid = goodsCategory.getPid();//分类id

			categoryIds.add(pid);
			categoryIds.add(categoryId);
		}


		//products
		GoodsProductExample productExample = new GoodsProductExample();
		GoodsProductExample.Criteria criteria = productExample.createCriteria();
		criteria.andGoodsIdEqualTo(goodsId);
		List<GoodsProduct> goodsProducts = productMapper.selectByExample(productExample);

		//specs
		GoodsSpecificationExample specificationExample = new GoodsSpecificationExample();
		GoodsSpecificationExample.Criteria criteria1 = specificationExample.createCriteria();
		criteria1.andGoodsIdEqualTo(goodsId);
		List<GoodsSpecification> goodsSpecifications = specificationMapper.selectByExample(specificationExample);

		//attribute
		GoodsAttributeExample attributeExample = new GoodsAttributeExample();
		GoodsAttributeExample.Criteria criteria2 = attributeExample.createCriteria();
		criteria2.andGoodsIdEqualTo(goodsId);
		List<GoodsAttribute> goodsAttributes = attributeMapper.selectByExample(attributeExample);

		GoodsDetailVO goodsDetailVO = new GoodsDetailVO();
		goodsDetailVO.setGoods(goods);
		goodsDetailVO.setCategoryIds(categoryIds);
		goodsDetailVO.setProducts(goodsProducts);
		goodsDetailVO.setSpecifications(goodsSpecifications);
		goodsDetailVO.setAttributes(goodsAttributes);
		return goodsDetailVO;
	}

	@Override
	public CatAndBrandVO getCatAndBrand() {
		CatAndBrandVO catAndBrandVO = new CatAndBrandVO();
		//获取品牌
		GoodsBrandExample brandExample = new GoodsBrandExample();
		GoodsBrandExample.Criteria criteria = brandExample.createCriteria();

		List<GoodsBrand> goodsBrands = brandMapper.selectByExample(brandExample);
		List<BrandListBean> brandList = catAndBrandVO.getBrandList();
		brandList=new ArrayList<>();
		for (GoodsBrand goodsBrand : goodsBrands) {
			BrandListBean brandListBean = new BrandListBean(goodsBrand.getId(), goodsBrand.getName());
			brandList.add(brandListBean);
		}

		//获取目录
		GoodsCategoryExample categoryExample = new GoodsCategoryExample();
		GoodsCategoryExample categoryExample2 = new GoodsCategoryExample();
		GoodsCategoryExample.Criteria criteria1 = categoryExample.createCriteria();
		GoodsCategoryExample.Criteria criteria2 = categoryExample2.createCriteria();
		criteria1.andDeletedEqualTo(false).andPidEqualTo(0);
		criteria2.andDeletedEqualTo(false).andPidNotEqualTo(0);
		List<GoodsCategory> goodsCategories = categoryMapper.selectByExample(categoryExample);//获取一级目录
		List<GoodsCategory> goodsCategoriesSub = categoryMapper.selectByExample(categoryExample2);//获取二级目录


		List<CategoryListBean> categoryList = new ArrayList<>();

		for (GoodsCategory goodsCategory : goodsCategories) {
			CategoryListBean categoryListBean = new CategoryListBean();
			Integer id = goodsCategory.getId();
			String name = goodsCategory.getName();
			categoryListBean.setLabel(name);
			categoryListBean.setValue(id);
			List<ChildrenBean> childrenBeanList=new ArrayList<>();

				for (GoodsCategory categorySub : goodsCategoriesSub) {
					if (categorySub.getPid().equals(id)){
						ChildrenBean childrenBean = new ChildrenBean();
						childrenBean.setValue(categorySub.getId());
						childrenBean.setLabel(categorySub.getName());
						childrenBeanList.add(childrenBean);
					}
				}
			categoryListBean.setChildren(childrenBeanList);
				categoryList.add(categoryListBean);

		}

		catAndBrandVO.setBrandList(brandList);
		catAndBrandVO.setCategoryList(categoryList);
		return catAndBrandVO;
	}

	/**
	 * 更新goods,product,specification,attribute
	 * @param updateGoodsBO
	 */
	@Override
	public void updateGoods(UpdateGoodsBO updateGoodsBO) {

		//新增商品
		//更新goods
		GoodsBeanX goodsBeanX = updateGoodsBO.getGoods();
		Goods goods=new Goods();
		goods.setId(goodsBeanX.getId());
		goods.setGoodsSn(goodsBeanX.getGoodsSn());
		goods.setBrandId(goodsBeanX.getBrandId());
		goods.setBrief(goodsBeanX.getBrief());
		goods.setName(goodsBeanX.getName());
		goods.setCounterPrice(new BigDecimal(goodsBeanX.getCounterPrice()));//字符串转BigDecimal
		goods.setRetailPrice(new BigDecimal(goodsBeanX.getRetailPrice()));//字符串转BigDecimal
		goods.setIsHot(goodsBeanX.isHot());
		goods.setIsNew(goodsBeanX.isNew());
		goods.setIsOnSale(goodsBeanX.isOnSale());
		goods.setUnit(goodsBeanX.getUnit());
		goods.setKeywords(goodsBeanX.getKeywords());
		goods.setCategoryId(goodsBeanX.getCategoryId());
		goods.setPicUrl(goodsBeanX.getPicUrl());
		goods.setDetail(goodsBeanX.getDetail());
		String join = String.join(",", goodsBeanX.getGallery());
		String[] split = join.split(",");
		goods.setGallery(split);
		goods.setDeleted(goodsBeanX.isDeleted());
		goods.setAddTime(Timestamp.valueOf(goodsBeanX.getAddTime()));
		goods.setUpdateTime(new Timestamp(System.currentTimeMillis()));
		goods.setShareUrl(goodsBeanX.getShareUrl());
		goods.setSortOrder(Short.parseShort(String.valueOf(goodsBeanX.getSortOrder())));
		goodsMapper.deleteByPrimaryKey(goods.getId());
		goodsMapper.insertSelective(goods);
//		goodsMapper.updateByPrimaryKeySelective(goods);

		//更新product
		List<ProductsBeanX> productsBeanXList = updateGoodsBO.getProducts();
		GoodsProductExample productExample = new GoodsProductExample();
		GoodsProductExample.Criteria productExampleCriteria = productExample.createCriteria();
		productExampleCriteria.andGoodsIdEqualTo(goodsBeanX.getId());
		productMapper.deleteByExample(productExample);
		for (ProductsBeanX productsBeanX : productsBeanXList) {

			GoodsProduct goodsProduct = new GoodsProduct();
			goodsProduct.setId(productsBeanX.getId());
			goodsProduct.setPrice(new BigDecimal(productsBeanX.getPrice()));
			goodsProduct.setNumber(Integer.valueOf(productsBeanX.getNumber()));//传的是string 要确保是数字
			goodsProduct.setUrl(productsBeanX.getUrl());
			//规格字符串链表转为字符串,以逗号分割
			String[] specSplit = String.join(",", productsBeanX.getSpecifications()).split(",");
			goodsProduct.setSpecifications(specSplit);
			goodsProduct.setGoodsId(goodsBeanX.getId());
			goodsProduct.setAddTime(Timestamp.valueOf(productsBeanX.getAddTime()));
			goodsProduct.setUpdateTime(new Timestamp(System.currentTimeMillis()));
			goodsProduct.setDeleted(goodsBeanX.isDeleted());

			productMapper.insertSelective(goodsProduct);
//			productMapper.updateByPrimaryKeySelective(goodsProduct);
		}

		//更新spec
		List<SpecificationsBeanX> specifications = updateGoodsBO.getSpecifications();
		GoodsSpecificationExample specificationExample = new GoodsSpecificationExample();
		GoodsSpecificationExample.Criteria specificationExampleCriteria = specificationExample.createCriteria();
		specificationExampleCriteria.andGoodsIdEqualTo(goodsBeanX.getId());
		specificationMapper.deleteByExample(specificationExample);
		for (SpecificationsBeanX specificationsBeanX : specifications) {
			GoodsSpecification goodsSpecification = new GoodsSpecification();
			goodsSpecification.setId(specificationsBeanX.getId());
			goodsSpecification.setGoodsId(goodsBeanX.getId());
			goodsSpecification.setSpecification(specificationsBeanX.getSpecification());
			goodsSpecification.setValue(specificationsBeanX.getValue());
			goodsSpecification.setPicUrl(specificationsBeanX.getPicUrl());
			goodsSpecification.setAddTime(Timestamp.valueOf(specificationsBeanX.getAddTime()));
			goodsSpecification.setUpdateTime(new Timestamp(System.currentTimeMillis()));
			goodsSpecification.setDeleted(specificationsBeanX.isDeleted());
			specificationMapper.insertSelective(goodsSpecification);
//			specificationMapper.updateByPrimaryKeySelective(goodsSpecification);
		}
		//更新attr
		List<AttributesBeanX> attributes = updateGoodsBO.getAttributes();
		GoodsAttributeExample attributeExample = new GoodsAttributeExample();
		GoodsAttributeExample.Criteria attributeExampleCriteria = attributeExample.createCriteria();
		attributeExampleCriteria.andGoodsIdEqualTo(goodsBeanX.getId());
		attributeMapper.deleteByExample(attributeExample);
		for (AttributesBeanX attributesBeanX : attributes) {
			GoodsAttribute goodsAttribute = new GoodsAttribute();
			goodsAttribute.setId(attributesBeanX.getId());
			goodsAttribute.setGoodsId(goodsBeanX.getId());
			goodsAttribute.setValue(attributesBeanX.getValue());
			goodsAttribute.setAttribute(attributesBeanX.getAttribute());
			goodsAttribute.setAddTime(new Timestamp(System.currentTimeMillis()));
			goodsAttribute.setUpdateTime(new Timestamp(System.currentTimeMillis()));
			goodsAttribute.setDeleted(attributesBeanX.isDeleted());
			attributeMapper.insertSelective(goodsAttribute);
//			attributeMapper.updateByPrimaryKeySelective(goodsAttribute);
		}

	}

	/**
	 * 假删除
	 * @param deleteGoodsBo
	 */
	@Override
	public void deleteGoods(DeleteGoodsBo deleteGoodsBo) {
		goodsMapper.deleteGoodsById(deleteGoodsBo.getId());
	}

	/**
	 * 判断库存是否足够 HJL
	 * @param productId
	 * @param demand
	 * @return
	 */
	@Override//return null 不足 ，方法复用 demand传如0就能查库存有多少
	public GoodsProduct hasEnoughStock(Integer productId, Integer demand) {
		GoodsProduct goodsProduct = productMapper.selectByPrimaryKey(productId);
		Integer stock = goodsProduct.getNumber();
		if (stock < demand) {
			return null;
		}
		return goodsProduct;
	}

	/**
	 * 更新库存 HJL
	 * 需要异常捕获处理器支持
	 * @param productId
	 * @param num + 加库存 - 减库存
	 */
	@Override
	public GoodsProduct updateProductStock(int productId, int num) throws SQLException {
		GoodsProduct goodsProduct;
		if (num < 0) {
			goodsProduct = hasEnoughStock(productId, -num);
			if (goodsProduct == null) {
				throw new SQLException("库存不足");//抛给处理器
			}
		} else {
			goodsProduct = productMapper.selectByPrimaryKey(productId);
		}
		GoodsProduct gp = new GoodsProduct();
		gp.setId(productId);
		Timestamp now = new Timestamp(System.currentTimeMillis());
		gp.setUpdateTime(now);
		gp.setNumber(goodsProduct.getNumber() + num);
		productMapper.updateByPrimaryKeySelective(gp);

		return productMapper.selectByPrimaryKey(productId);
	}

	/**
	 * 判断是否存在商品
	 * @param goodsId
	 * @return
	 */
	@Override
	public Boolean contains(String goodsId) {

		Goods goods = goodsMapper.selectByPrimaryKey(Integer.parseInt(goodsId));

		return goods != null;
	}


}